<template>
  <div class="components-container main-container">
    <el-row>
      <el-steps :active="active"  align-center>
        <el-step title="步骤 1" description="填写请假单" icon="el-icon-edit"></el-step>
        <el-step title="步骤 2" description="人脸校验" icon="el-icon-upload"></el-step>
        <el-step title="步骤 3" description="开始审核流程" icon="el-icon-picture"></el-step>
      </el-steps>
    </el-row>
    <el-row style="margin-top: 50px;margin-left: 100px;">
      <el-col :span="24">
        <el-form  ref="leave_form" :label-position="'top'" :rules="rules" :model="leave" class="demo-form-inline">
          <el-form-item label="选择日期" prop="startAndEndTime">
            <el-date-picker
              v-model="leave.startAndEndTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              unlink-panels
              align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="指定代办人" prop="judgeId">
            <el-select v-model="leave.judgeId" placeholder="选择代办人">
              <el-option
                v-for="item in judgeIds"
                :key="item.guid"
                :label="item.name"
                :value="item.guid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="reason">
            <textarea style="margin-top: 20%" id="tinymceId" v-model="reason" />
          </el-form-item>
          <el-form-item>
            <el-button size="medium" type="primary" @click="save">提交</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-dialog @close="closeVideo" :destroy-on-close="true"  width="30%" title="身份识别" :visible.sync="showFace">
      <face-camera  @success="checkSuccess" ref="camera"></face-camera>
    </el-dialog>
  </div>
</template>

<script>
  import load from '../rich-editor/tinymce-components/dynamicLoadScript'
  import toolbar from '../rich-editor/tinymce-components/toolbar'
  import plugins from '../rich-editor/tinymce-components/plugins'

  // why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
  const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
  function checkStartTime(rule,value,callback) {
    let date=new Date();
    if (value<date){
      return callback(new Error("不得早于当前时间"));
    }else{
      return callback();
    }
  }
  export default {
    name: 'Publish',
    data() {
      return {
        faceBase64:'',
        showFace:false,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        reason:'',
        judgeIds:[{name:'管理员',guid:'admin'}],
        startAndEndTime:'',
        active:0,// 进度条
        hasChange: false,
        hasInit: false,
        tinymceId: 'tinymceId',
        height: 360,
        toolbar: [],
        menubar: 'file edit insert view format table',
        languageTypeList: {
          'en': 'en',
          'zh': 'zh_CN'
        },
        leave:{startAndEndTime:'',judgeId:'',
          reason: '',},
        // 富文本内容
        rules: {
          startAndEndTime: [
            { required: true, message: '请选择起始时间', trigger: 'change' }
          ],
          judgeId: [
            {  required: true, message: '至少选择一位代办人', trigger: 'change' }
          ]
        },
        postForm:{},
      }
    },
    watch: {
      content(val) {
        if (!this.hasChange && this.hasInit) {
          this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val || ''))
        }
      }
    },
    methods: {
      checkSuccess(imgStr){
        let g=this;
        g.$set(g.postForm,'leaveImageContent',imgStr);
        g.$nextTick(()=>{
          g.$ajaxPost(`/faceInformation/judgeBeforePublishLeave?studentNo=${g.$store.getters.userId}`,{data:imgStr}).then(res=>{
            g.message({message:"校验通过,正在发布假条",type:'success',onClose:()=>{
                g.$ajaxPost('/leave/publish',g.postForm).then(res=>{
                  g.$alert('发布成功', '结果', {
                    confirmButtonText: '确定',
                    callback: action => {
                      g.postForm={};
                      g.closeVideo();
                      g.showFace=false;
                    }
                  });
                }).catch(()=>{
                  g.postForm={};
                  g.closeVideo();
                  g.showFace=false;
                })
              }});
        })
      })
      },
      closeVideo(){
        this.$refs.camera.closeVideo();
      },
      init() {
        // dynamic load tinymce from cdn
        load(tinymceCDN, (err) => {
          if (err) {
            this.$message.error(err.message)
            return
          }
          this.initTinymce()
        })
      },
      initTinymce() {
        const _this = this
        window.tinymce.init({
          selector: `#${this.tinymceId}`,
          language: this.languageTypeList['zh'],
          height: this.height,
          body_class: 'panel-body ',
          object_resizing: false,
          toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
          plugins,
          width:723,
          height:300,
          menubar: this.menubar,
          end_container_on_empty_block: true,
          powerpaste_word_import: 'clean',
          code_dialog_height: 100,
          code_dialog_width: 1000,
          advlist_bullet_styles: 'square',
          advlist_number_styles: 'default',
          imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
          default_link_target: '_blank',
          link_title: false,
          nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
          init_instance_callback: editor => {
            if (_this.content) {
              editor.setContent(_this.content)
            }
            _this.hasInit = true
            editor.on('NodeChange Change KeyUp SetContent', () => {
              this.hasChange = true
              this.content = editor.getContent()
            })
          },
          setup(editor) {
            editor.on('FullscreenStateChanged', (e) => {
              _this.fullscreen = e.state
            })
          }
        })
      },
      destroyTinymce() {
        const tinymce = window.tinymce.get(this.tinymceId)
        if (this.fullscreen) {
          tinymce.execCommand('mceFullScreen')
        }
        if (tinymce) {
          tinymce.destroy()
        }
      },
      //保存
      save(){
        let g=this;
        g.postForm={studentNo:this.$store.getters.userId,leaveStartTime:'',leaveEndTime:'',validFlag:0
          ,judgeId:'',leaveReason:'',leaveImageContent:''};
        this.$refs.leave_form.validate(valid=>{
          if (valid){
            var activeEditor = window.tinymce.activeEditor;
            var editBody = activeEditor.getBody();
            activeEditor.selection.select(editBody);
            var text = activeEditor.selection.getContent( { 'format' : 'text'} );
            let dayDifference=Math.floor((g.leave.startAndEndTime[1].getTime()-g.leave.startAndEndTime[0].getTime())/(24*3600*1000));
            if (g.isNullOrEmpty(text)){
              g.message({message:'请假事由不得为空',type:'warning'});
              return;
            }
            if (dayDifference>=7 && g.leave.judgeId!='admin'){
              g.message({message:'时间周期大于七天，只能选择管理员审核',type:'warning'});
              return;
            }else{
              g.$set(g.postForm,'leaveStartTime',g.leave.startAndEndTime[0].getTime());
              g.$set(g.postForm,'leaveEndTime',g.leave.startAndEndTime[1].getTime());
              g.$set(g.postForm,'judgeId',g.leave.judgeId);
              g.$set(g.postForm,'leaveReason',text);
              g.showFace=true;
              g.$nextTick(()=>{
                g.$refs.camera.openVideo();
              })
            }

          }else{

          }
        })

      },
      loadAssiants(){
        let g=this;
        g.$ajaxGet(`/student/getAssiantByUserName/${g.$store.getters.userId}`).then(res=>{
          g.judgeIds.push(res);
        })
      }

    },
    created(){
      this.loadAssiants();
    },
    mounted() {
      this.init()
    },
    beforeDestroy() {
      this.destroyTinymce()
    },
    activated() {
      if(window.tinymce) {
        this.initTinymce()
      }
    },
    deactivated() {
      this.destroyTinymce()
    }
  }
</script>

<style scoped>
  .main-container {
    max-width: 80%;
    min-width: 800px;
  }
  .tinymce-container {
    position: relative;
    line-height: normal;
  }
  .tinymce-container>>>.mce-fullscreen {
    z-index: 10000;
  }
  .tinymce-textarea {
    visibility: hidden;
    z-index: -1;
  }
</style>
